#include "TImage.h" 
#include "../utils/Utils.h"
#include "TUI.h"



TImage::TImage(){
    m_pItem=NULL;
}

TImage* TImage::create(xml_node<> * pItem){
    TImage*  ret=TImage::create();
    ret->initWidthConf(pItem);
    return ret;
}

void TImage::setSource(const char* path, int customWidth, int customHeight){
    
   
    
    if(PACK_ASSETS_PLIST){
        if(!CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(path)){
            return;
        }
        if(m_pItem==NULL){
            m_pItem=CCSprite::createWithSpriteFrameName(path );
            m_pItem->setCascadeOpacityEnabled(true);
            addChild(m_pItem);
        }else{
            m_pItem->setDisplayFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(path));
        }
    }else{
        if(m_pItem==NULL){
            m_pItem=CCSprite::create(path);
            m_pItem->setCascadeOpacityEnabled(true);
            addChild(m_pItem);
        }else{
            m_pItem->initWithFile(path);
        }
        
    }
    

	int width=m_pItem->getContentSize().width;
    int height=m_pItem->getContentSize().height;
	if(customWidth > 0) {
		m_pItem->setScaleX(customWidth * 1.0f / width);
	}
	if(customHeight > 0) {
		m_pItem->setScaleY(customHeight * 1.0f / height);
	}
	m_pItem->setPositionX(m_pItem->getContentSize().width* m_pItem->getScaleX()/2);
    m_pItem->setPositionY(- m_pItem->getContentSize().height* m_pItem->getScaleY()/2);
    setContentSize(CCSizeMake(m_pItem->getContentSize().width* m_pItem->getScaleX(),
                              m_pItem->getContentSize().height* m_pItem->getScaleY()
                              )
                   );
}

void TImage::initWidthConf(xml_node<> * pItem){
    string path;
    readAttrString(pItem, "source", path);
	CCSize size=readContainSize(pItem, getParent());
    setSource(path.c_str(), size.width, size.height);
    
}

void TImage::setPath( const char* path )
{
	
	if(m_pItem==NULL){
		m_pItem=CCSprite::create(path );
		if(!m_pItem) {
			return;
		}
		m_pItem->setCascadeOpacityEnabled(true);
		addChild(m_pItem);
	} else {
		m_pItem->initWithFile(path);
	}
	m_pItem->setVisible(true);
}
